package plus.easydo.easypush.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import plus.easydo.easypush.entity.UserInfo;
import plus.easydo.easypush.entity.UserPlatform;
import plus.easydo.easypush.mapper.UserPlatformMapper;
import plus.easydo.easypush.service.UserInfoService;
import plus.easydo.easypush.mapper.UserInfoMapper;
import org.springframework.stereotype.Service;
import plus.easydo.easypush.vo.UserInfoVo;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 *
 * @author yuzhanfeng
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{

    @Autowired
    UserPlatformMapper userPlatformMapper;


    @Override
    public UserInfoVo getUserInfoByUnionIdAndPlatform(String unionId, String platform) {
        LambdaQueryWrapper<UserPlatform> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserPlatform::getUnionId,unionId);
        wrapper.eq(UserPlatform::getPlatform,platform);
        UserPlatform userPlatform = userPlatformMapper.selectOne(wrapper);
        if(Objects.nonNull(userPlatform)){
            Long userId = userPlatform.getUserId();
            UserInfo userInfo = baseMapper.selectById(userId);
            UserInfoVo vo = new UserInfoVo();
            BeanUtil.copyProperties(userInfo,vo);
            BeanUtil.copyProperties(userPlatform,vo);
            return vo;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoVo createUser(AuthUser authUser) {
            String source = authUser.getSource();
            String nickname = authUser.getNickname();
            String unionId = authUser.getUuid();
            String avatar = authUser.getAvatar();
            UserInfo userInfo = UserInfo.builder().secret(UUID.fastUUID().toString(true))
                    .createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).build();
            baseMapper.insert(userInfo);
            UserPlatform userPlatform = UserPlatform.builder()
                    .userId(userInfo.getId()).unionId(unionId).nickName(nickname).avatarUrl(avatar).platform(source)
                    .createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).build();
            userPlatformMapper.insert(userPlatform);
            userInfo.setPlatform(source);
            UserInfoVo vo = new UserInfoVo();
            BeanUtil.copyProperties(userInfo,vo);
            BeanUtil.copyProperties(userPlatform,vo);
            return vo;
    }
}




